package io.github.wanggit.antcms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.wanggit.antcms.server.domain.AntArticle;
import io.github.wanggit.antcms.server.domain.AntArticleTag;
import io.github.wanggit.antcms.server.domain.AntTag;
import io.github.wanggit.antcms.server.mapper.AntTagMapper;
import io.github.wanggit.antcms.server.service.ArticleTagService;
import io.github.wanggit.antcms.server.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class TagServiceImpl extends ServiceImpl<AntTagMapper, AntTag> implements TagService {

    @Autowired private ArticleTagService articleTagService;

    @Override
    public Page<AntTag> listTags(Integer page, Integer size, String name, String aliasName) {
        Page<AntTag> pageEntity = new Page<>(page, size);
        QueryWrapper<AntTag> queryWrapper = new QueryWrapper<>();
        if (null != name) {
            queryWrapper.like("name", name);
        }
        if (null != aliasName) {
            queryWrapper.like("alias_name", aliasName);
        }
        queryWrapper.orderByDesc("update_time");
        return page(pageEntity, queryWrapper);
    }

    @Override
    public void saveOrUpdateTag(AntTag tag) {
        QueryWrapper<AntTag> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", tag.getName());
        int cnt = count(queryWrapper);
        if (cnt == 0) {
            if (!StringUtils.hasText(tag.getAliasName())) {
                tag.setAliasName(tag.getName());
            }
            save(tag);
        }
    }

    @Override
    public List<AntTag> findTagByArticle(AntArticle article) {
        List<AntArticleTag> articleTags = articleTagService.findRelationsByArticle(article);
        List<Long> tagIds =
                articleTags.stream().map(AntArticleTag::getTagId).collect(Collectors.toList());
        return tagIds.isEmpty() ? new ArrayList<>() : listByIds(tagIds);
    }
}
